package org.common.aspect;

/**
 * ClassName: LogInfoAspect
 * Package: org.common.aspect
 * Description:
 *
 * @Author: @weixueshi
 * @Create: 2024/7/19 - 11:38
 * @Version: v1.0
 */

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.common.annotation.RedisLimitAnnotation;
import org.common.exception.SystemException;
import org.common.response.ResponseCodeEnum;
import org.common.response.ResultData;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义限流切面
 */
@Slf4j
@Aspect
@Component
public class RedisLimitAspect {

    Object result = null;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private DefaultRedisScript<Long> redisLuaScript;

    /**
     * 加载lua脚本
     */
    @PostConstruct
    public void init(){
        redisLuaScript = new DefaultRedisScript<>();
        redisLuaScript.setResultType(Long.class);
        redisLuaScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("rateLimiter.lua")));
    }

    /**
     * 环绕通知
     * @param joinPoint 切点
     * @return Object
     */
    @Around("@annotation(org.common.annotation.RedisLimitAnnotation)")
    public Object redisLimitAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取方法上的注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RedisLimitAnnotation limitAnnotation = method.getAnnotation(RedisLimitAnnotation.class);

        if(limitAnnotation != null){
            //获取注解的参数
            //获取限流的唯一key
            String key = limitAnnotation.key();
            String className = method.getDeclaringClass().getName();
            String methodName = method.getName();

            //构造redis的key
            String limitKey = key + "\t" + className + "\t" + methodName;
            log.info("限流key：{}",limitKey);

            //key必须设置
            if(key == null){
                log.error("限流key不能为空");
                throw new SystemException(ResponseCodeEnum.KEY_NOT_EXIST);
            }

            //获取最大访问次数
            long maxRestrictions = limitAnnotation.maxRestrictions();
            //获取过期时间
            long expireTime = limitAnnotation.expireTime();

            List<String> keys = new ArrayList<>();
            keys.add(key);

            Long count = stringRedisTemplate.execute(
                    redisLuaScript,
                    keys,
                    String.valueOf(maxRestrictions),
                    String.valueOf(expireTime));

            log.info("当前访问次数：{}；key：{}",count,key);
            if(count != null && count == 0){
                log.error("触发限流机制！{}",key);
                return ResultData.fail(ResponseCodeEnum.FAIL.getCode(),limitAnnotation.message());
            }
        }

        //执行目标方法
        result = joinPoint.proceed();
        return result;
    }
}
